package com.qk.management.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.qk.common.PageResult;
import com.qk.common.util.JwtUtils;
import com.qk.domain.user.UserDO;
import com.qk.dto.user.UserDTO;
import com.qk.dto.user.UserLoginDTO;
import com.qk.entity.Role;
import com.qk.entity.User;
import com.qk.management.mapper.RoleMapper;
import com.qk.management.mapper.UserMapper;
import com.qk.management.service.UserService;
import com.qk.vo.user.UserLoginVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @author: hm
 * @Date: 2025/10/07 18:29
 * @Description:
 */
@Service
@SuppressWarnings("all")
public class UserServiceImpl implements UserService {
    private static final String DEFAULT_PASSWORD_SuFIX = "123";
    private static final Integer DEFAULT_STATUS_UNNORMAL = 0;

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RoleMapper roleMapper;

    @Override
    public List<User> getByDeptId(Integer deptId) {
        List<User> users = userMapper.selectByDeptId(deptId);
        return users;
    }

    @Override
    public List<User> getByRoleLabel(String roleLabel) {
        Role role = roleMapper.selectByRoleLabel(roleLabel);
        boolean isNull = Objects.isNull(role);
        if (isNull){
            throw new RuntimeException("角色不存在!");
        }
        List<User> users = userMapper.selectByRoleId(role.getId());
        return users;
    }

    @Override
    public List<User> getAllUsers() {
        return userMapper.selectAllUsers();
    }

    @Override
    public void update(User user) {
        String updatedPassword = DigestUtils.md5DigestAsHex(user.getPassword().getBytes());
        user.setPassword(updatedPassword);
        userMapper.update(user);
    }

    @Override
    public User getById(Integer id) {
        User user = userMapper.selectById(id);
        return user;
    }

    @Override
    public void deleteBatch(List<Integer> ids) {
        userMapper.deleteBatch(ids);
    }

    @Override
    public UserLoginVo login(UserLoginDTO dto) {

        boolean hasNull = BeanUtil.hasNullField(dto);
        if (hasNull){
            throw new RuntimeException("参数错误!");
        }
        User dbUser = userMapper.selectByUsername(dto.getUsername());
        if (ObjectUtil.isNull(dbUser)){
            throw new RuntimeException("用户不存在!");
        }
        if (ObjectUtil.equal(dbUser.getStatus(), DEFAULT_STATUS_UNNORMAL)){
            throw new RuntimeException("用户被停用!");
        }
        String userPassword = DigestUtils.md5DigestAsHex(dto.getPassword().getBytes());
        boolean isChecked = ObjectUtil.equal(userPassword, dbUser.getPassword());
        if (!isChecked){
            throw new RuntimeException("密码错误!");
        }
        Role role = roleMapper.selectById(dbUser.getRoleId());

        Map<String, Object> claims = new HashMap<>();
        claims.put("id",dbUser.getId());
        claims.put("username",dbUser.getUsername());

        return UserLoginVo.builder()
                .id(dbUser.getId())
                .username(dbUser.getUsername())
                .name(dbUser.getName())
                .image(dbUser.getImage())
                .roleLabel(role.getLabel())
                .token(JwtUtils.generateToken(claims))
                .build();
    }

    @Override
    public void addUser(User user) {
        //校验数据
        boolean hasNull = BeanUtil.hasNullField(user, "id","password", "deptId", "roleId", "image", "remark", "createTime", "updateTime");
        if (hasNull){
            throw new RuntimeException("参数错误");
        }
        user.setCreateTime(LocalDateTime.now());
        user.setUpdateTime(LocalDateTime.now());
        String rawPassword = new StringBuilder(user.getUsername()).append(DEFAULT_PASSWORD_SuFIX).toString();
        String encodedPassword = DigestUtils.md5DigestAsHex(rawPassword.getBytes());
        user.setPassword(encodedPassword);
        userMapper.insert(user);
    }

    @Override
    public PageResult<UserDO> list(UserDTO dto) {
        //参数校验
        //开启分页
        PageHelper.startPage(dto.getPage(), dto.getPageSize());
        //查询
        List<UserDO> page = userMapper.selectByPage(dto);
        Page<UserDO> result = (Page<UserDO>) page;
        //封装数据
        return PageResult.<UserDO>builder()
                .total(result.getTotal())
                .rows(result.getResult())
                .build();
    }
}
